﻿@inherits _BaseView

<MudRTLProvider RightToLeft="@SharedLayoutSettings.IsRTL">
    <EditForm OnValidSubmit="OnSubmit" Model="SubmitRoleViewModel">
        <DataAnnotationsValidator />
        <MudDialog>
            <DialogContent>
                @if (!IsLoaded)
                {
                    <FormOverlay />
                }
                else
                {
                    <MudCard Class="mt-2">
                        <MudPaper Elevation="25">
                            <MudToolBar Dense>
                                <MudText Color="Color.Primary">
                                    @DashboardResource.StringRole
                                </MudText>
                                <MudSpacer />
                                <MudIconButton Disabled="@IsProcessing" ButtonType="ButtonType.Submit" Icon="@Icons.Material.Filled.Save" Color="Color.Tertiary" title="@DashboardResource.StringCreate">
                                    @if (IsProcessing)
                                    {
                                        <MudProgressCircular Size="Size.Small" Indeterminate="true" Class="ms-n1" />
                                        <MudText Class="ms-2">@DashboardResource.StringProcessing</MudText>
                                    }
                                    else
                                    {
                                        <MudIcon Icon="@Icons.Material.Filled.Save" Color="Color.Surface" Class="mx-1" />
                                        <MudText>@DashboardResource.StringSave</MudText>
                                    }
                                </MudIconButton>
                                <MudIconButton OnClick="Close" Icon="@Icons.Material.Filled.Close" Color="Color.Error" title="@DashboardResource.StringCancel" />
                            </MudToolBar>
                        </MudPaper>
                        <MudDivider DividerType="DividerType.FullWidth" />
                        <MudCardContent>
                            <MudGrid>
                                <MudItem md="6" xs="6">
                                    <MudTextField @bind-Value="SubmitRoleViewModel.Role" Variant="Variant.Outlined"
                                                  Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Title" Clearable
                                                  For="@(() => SubmitRoleViewModel.Role)"
                                                  Label="@DashboardResource.StringRole" />
                                </MudItem>
                            </MudGrid>
                        </MudCardContent>
                    </MudCard>
                }
            </DialogContent>
        </MudDialog>
    </EditForm>
</MudRTLProvider>

@code {

    [CascadingParameter]
    public MudDialogInstance MudDialog { get; set; }

    private void Close() => MudDialog.Close();

    // *****************************************************

    [Parameter]
    public string Id { get; set; }

    private SubmitRoleViewModel SubmitRoleViewModel = new();

    protected async override Task OnInitializedAsync()
    {
        IsLoaded = false;

        try
        {
            if (!string.IsNullOrEmpty(Id) && Id != "0")
            {
                var Callback = await Http.GetFromJsonAsync<CallbackResult<IdentityRole>>($"api/Roles/Details/{Id}");
                if (Callback.Data != null)
                {
                    SubmitRoleViewModel.Id = Callback.Data.Id;
                    SubmitRoleViewModel.Role = Callback.Data.Name;
                }
                else
                {
                    Snackbar.Add(Callback.Error.ToString(), Severity.Error);
                }
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"{DashboardResource.StringError} : " + ex.Message, Severity.Error);
        }

        IsLoaded = true;
    }

    private async Task OnSubmit()
    {
        if (IsProcessing)
            return;
        IsProcessing = true;

        try
        {
            if (Id == "0")
            {
                var PostResult = await Http.PostAsJsonAsync("api/Roles/Create", SubmitRoleViewModel.TrimStringAndCheckPersianSpecialLetter());
                if (PostResult.IsSuccessStatusCode)
                {
                    var JsonResult = await PostResult.Content.ReadFromJsonAsync<CallbackResult<SubmitRoleViewModel>>();
                    if (JsonResult?.Data != null)
                    {
                        Snackbar.Add(JsonResult.SuccessMessage ?? DashboardResource.MessageSavedSuccessfully, Severity.Success);
                        MudDialog.Close(DialogResult.Ok(SubmitRoleViewModel));
                    }
                    else
                    {
                        Snackbar.Add(MessageHandler.ErrorHandler(JsonResult.Error), Severity.Error);
                    }
                }
                else
                {
                    Snackbar.Add(PostResult.Content.ReadAsStringAsync().Result, Severity.Error);
                }
            }
            else
            {
                var PutResult = await Http.PutAsJsonAsync("api/Roles/Edit", SubmitRoleViewModel.TrimStringAndCheckPersianSpecialLetter());
                if (PutResult.IsSuccessStatusCode)
                {
                    var JsonResult = await PutResult.Content.ReadFromJsonAsync<CallbackResult<SubmitRoleViewModel>>();
                    if (JsonResult.Data != null)
                    {
                        Snackbar.Add(JsonResult.SuccessMessage ?? DashboardResource.MessageSavedSuccessfully, Severity.Success);
                        MudDialog.Close(DialogResult.Ok(SubmitRoleViewModel));
                    }
                    else
                    {
                        Snackbar.Add(MessageHandler.ErrorHandler(JsonResult.Error), Severity.Error);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add($"{DashboardResource.StringError} : " + ex.Message, Severity.Error);
        }

        IsProcessing = false;
    }

}
